<?php

require_once 'lib/dsn.class.php';

class Controller {
	
	public $templateVars = array();
	
	private $db;
	public $FB;
	public $FB_session;
	
	protected function session_read($name) {
		return $_SESSION["YAMB"][$name];
	}
	protected function session_write($name, $value) {
		$_SESSION["YAMB"][$name] = $value;
	}
	protected function _getPlayer() {
		$player = $this->session_read("player");
		return $player ? $player : false;
	}
	protected function _getFBPlayer() {
		$player = $this->FB->getUser();
		return $player ? $player : false;
	}
	
	/*****************************************************************/
	
	public function __construct() {
		$this->db = DSN::_getConnection();
		
		// Facebook API
		Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
		Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;
		$this->FB = new Facebook(array(
			'appId'  => FB_APPID,
			'secret' => FB_SECRET,
			'cookie' => true, 
		));
		
		$session = $this->FB->getSession();
		$me = null;
		
		if($session) {
			try {
				$me = $this->FB->api("/me");
			}catch(FacebookApiException $e) {
				
			}
		}
		if(!$me) {
			$this->FB->setSession(null);
		}
		$this->set("fb_me", $me);
	}
	
	public function set($name, $value) {
		$this->templateVars[$name] = $value;
	}
	
	public function display($view) {
		$template = $this->fetch($view);
		echo $template;
	}
	
	public function fetch($view) {
		
		$path = DIR_VIEWS . '/' . $view . ".ctp";
		foreach($this->templateVars as $k=>$v) {
			$$k = $v;
		}
		$prev = ob_get_contents();
		ob_clean();
		include_once $path;
		$ret = ob_get_contents();
		ob_clean();
		
		echo $prev;
		return $ret;
	}
	
	public function db_query($sql) {
		$ret = array();
		$res = mysql_query($sql, $this->db);
		if($res) {
			if(mysql_num_rows($res)) {
				while($row = mysql_fetch_assoc($res)) {
					$ret[] = $row;
				}
			}
		}else{
			//TODO: Log mysql error
		}
		return $ret;
	}
	public function db_exec($sql) {
		$ret = 0;
		$res = mysql_query($sql, $this->db);
		if($res) {
			$ret = mysql_affected_rows($this->db);
		}
		return $ret;
	}
	public function sendMail($to, $subject, $message) {
		$headers = 'From: "Yamb.info"<no-reply@yamb.info>'."\n"
				  .'Content-Type: text/html; charset=utf-8'."\n";
		
		//return mail($to,$subject,$message,$headers);
		//file_put_contents("mail.tarpit", "\n\n\n\n-----\n".date("d.m.Y H:i:s")."\n-----\nTo:$to\nSubject:$subject\n\n$message", FILE_APPEND);return true;
	}
}

?>